﻿using System;
using System.Reflection;
using UnityEngine;

namespace IQIGame.Onigao.Framework
{
    public static class ReflectionUtility
    {
        private static string GetAssemblyPath(string assemblyName)
        {
#if UNITY_EDITOR
            string dataPath = Application.dataPath;
            string projectPath = dataPath.Substring(0, dataPath.Length - "Assets".Length - 1);
            string finalPath = $"{projectPath}/Library/ScriptAssemblies/{assemblyName}";
            return finalPath;
            //TODO #else
#else
            return "";
#endif
        }

        private static Type GetType(string assemblyName, string classFullName)
        {
            // 加载一个没有被当前程序集引用的程序集
            Assembly myAssembly = Assembly.LoadFile(GetAssemblyPath(assemblyName));
            // 获取程序集中的某个类型
            Type type = myAssembly.GetType(classFullName);
            return type;
        }

        public static void CallStaticMethod(string assemblyName, string classFullName, string methodName, params object[] parameters)
        {
            Type type = GetType(assemblyName, classFullName);
            MethodInfo method = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static);
            method.Invoke(null, parameters);
        }

        public static void NewObjAndCallMethod(string assemblyName, string classFullName, string methodName, params object[] parameters)
        {
            Type type = GetType(assemblyName, classFullName);
            // 创建类型的实例
            object obj = Activator.CreateInstance(type);
            // 调用类型的方法
            MethodInfo method = type.GetMethod(methodName);
            method.Invoke(obj, parameters);
        }
    }
}
